package cn.flying.base.process.listener.eventlistener;

import javax.annotation.Resource;

import java.util.Comparator;
import java.util.Map;
import java.util.Objects;

import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import cn.flying.base.process.listener.entity.TaskCreateEntity;
import cn.flying.base.process.listener.handler.TaskCreatedListenerHandler;


/**
 * @description: 任务创建监听
 * @author: lvyong
 * @date: 2023年02月26日 08:24
 * @version: 1.0
 */
@Component
public class TaskCreatedListener implements ActivitiEventListener {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ApplicationContext applicationContext;

    /**
     * Called when an event has been fired
     *
     * @param event the event
     */
    @Override
    public void onEvent(ActivitiEvent event) {
        logger.info("任务创建监听执行----start----");
        ActivitiEntityEventImpl entityEvent = (ActivitiEntityEventImpl) event;
        TaskEntityImpl taskEntity = (TaskEntityImpl) entityEvent.getEntity();
        ExecutionEntity processInstance = taskEntity.getProcessInstance();

        Map<String, TaskCreatedListenerHandler> beans = applicationContext.getBeansOfType(TaskCreatedListenerHandler.class);
        if (Objects.isNull(beans)) {
            return;
        }
        TaskCreateEntity entity = new TaskCreateEntity();
        entity.setTaskId(taskEntity.getId());
        entity.setTaskName(taskEntity.getName());
        entity.setTaskCreateTime(taskEntity.getCreateTime());
        entity.setTaskDefKey(taskEntity.getTaskDefinitionKey());
        entity.setProcessInstId(taskEntity.getProcessInstanceId());
        entity.setProcessDefId(taskEntity.getProcessDefinitionId());
        entity.setProcessDefKey(taskEntity.getTaskDefinitionKey());
        entity.setExecutionId(taskEntity.getExecutionId());
        entity.setBizKey(processInstance.getBusinessKey());
        entity.setProcessVariables(processInstance.getProcessVariables());
        entity.setTenantId(taskEntity.getTenantId());

        //执行实际的监听处理逻辑
        beans.values().stream().sorted(Comparator.comparing(TaskCreatedListenerHandler::order)).forEach(h -> h.handler(entity));
        logger.info("任务创建监听执行----end----");
    }

    /**
     * @return whether or not the current operation should fail when this listeners execution throws an exception.
     */
    @Override
    public boolean isFailOnException() {
        return false;
    }
}
